/**
 * 将类转换为样式
 * 处理三种情况：
 * 1. 变量绑定的类名
 * 2. 全局和当前文件已定义的样式
 * 3. Tailwind 类名
 */

import { IPublicTypeJSExpression } from '@alilc/lowcode-types';
import { EnhancedStyleTransformer } from '../utils/tailwind/enhancedTailwindTransformer';

interface ClassToStyleOptions {
  globalStyles?: Record<string, string>;
  fileStyles?: Record<string, string>;
  variables?: Record<string, any>;
}

export interface ClassToStyleResult {
  style?: Record<string, string>;
  className?: string | IPublicTypeJSExpression;
}

export function classToStyle(
  className: string | IPublicTypeJSExpression,
  options: ClassToStyleOptions = {},
): ClassToStyleResult {
  const { globalStyles = {}, fileStyles = {}, variables = {} } = options;
  const result: ClassToStyleResult = {};

  // 如果是 JSExpression 类型，暂时返回空对象
  if (typeof className !== 'string') {
    return {};
  }

  // 1. 处理变量绑定的类名
  if (className.includes('${')) {
    // 返回空对象，由上层处理变量绑定
    return {};
  }

  // 2. 处理已定义的样式
  const definedStyle = fileStyles[className] || globalStyles[className];
  if (definedStyle) {
    return typeof definedStyle === 'string' ? { className: definedStyle } : definedStyle;
  }

  // 3. 处理 Tailwind 类名
  const tailwindClasses = className.split(/\s+(?![^\[]*\])/).filter(Boolean);
  if (tailwindClasses.length > 0) {
    const { style, unconvertedClasses } = EnhancedStyleTransformer.toInlineStyle(tailwindClasses);
    return {
      style,
      className: unconvertedClasses.length > 0 ? unconvertedClasses.join(' ') : undefined,
    };
  }

  return result;
}
